package com.lcq.gulimall.coupon.service.impl;

import com.lcq.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.lcq.gulimall.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcq.common.utils.PageUtils;
import com.lcq.common.utils.Query;

import com.lcq.gulimall.coupon.dao.SeckillSessionDao;
import com.lcq.gulimall.coupon.entity.SeckillSessionEntity;
import com.lcq.gulimall.coupon.service.SeckillSessionService;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {
    @Autowired
    SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getLate3DaySession() {
        List<SeckillSessionEntity> sessions = this.baseMapper.selectList(new QueryWrapper<SeckillSessionEntity>()
                .between("start_time", startTime(), endTime()));
        for (SeckillSessionEntity session : sessions) {
            List<SeckillSkuRelationEntity> skuRelationEntities  = seckillSkuRelationService.getBaseMapper()
                    .selectList(new QueryWrapper<SeckillSkuRelationEntity>()
                    .eq("promotion_session_id", session.getId()));
            session.setRelationSkus(skuRelationEntities);
        }
        return sessions;
    }

    private String startTime(){
        return LocalDateTime.of(LocalDate.now(), LocalTime.MIN).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    private String endTime(){
        return LocalDateTime.of(LocalDate.now(), LocalTime.MIN).plusDays(2).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

}